<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="dialogVisible"
    :title="title"
    width="1000px"
    @close="close()"
  >
    <button-group
      ref="buttonGroup"
      @submitForm="submitForm('ruleForm')"
      @cancel="dialogVisible = false"
    />
    <div class="formTopFont">生产领料单</div>
    <el-row>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="领料" name="1">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-width="90px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="领料单号" prop="pickNo">
                  <el-input
                    v-model="ruleForm.pickNo"
                    maxlength="20"
                    :disabled="title === '编辑' && ruleForm.status !== 1"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料" prop="materialId">
                  <el-select
                    v-model="ruleForm.materialId"
                    size="mini"
                    :disabled="title === '编辑' && ruleForm.status !== 1"
                    style="width: 100%"
                    filterable
                  >
                    <el-option
                      v-for="item in materialAll"
                      :key="item.id"
                      :value="item.id"
                      :label="
                        item.materialName +
                        `${
                          item.materialCode !== ''
                            ? '-【' + item.materialCode + '】'
                            : ''
                        }`
                      "
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请人" prop="applyId">
                  <el-select
                    v-model="ruleForm.applyId"
                    style="width: 100%"
                    filterable
                  >
                    <el-option
                      v-for="item in userAllList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="申请时间" prop="applyDate">
                  <el-date-picker
                    v-model="ruleForm.applyDate"
                    type="date"
                    placeholder="选择日期时间"
                    style="width: 100%"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请数量" prop="applyNum">
                  <el-input-number
                    v-model="ruleForm.applyNum"
                    :disabled="title === '编辑' && ruleForm.status !== 1"
                    size="mini"
                    :controls="false"
                    :min="1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="作业车间" prop="factoryId">
                  <tree-select
                    ref="treeSelect"
                    style="width: 100%"
                    :props="treeProps"
                    :disabled="title === '编辑' && ruleForm.status !== 1"
                    :options="factoryData"
                    :accordion="true"
                    :value="ruleForm.factoryId"
                    search-key="factoryName"
                    @getNode="getValue($event)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8" v-if="title === '编辑'">
                <el-form-item label="来料数量" prop="incomingNum">
                  <el-input v-model="ruleForm.incomingNum" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                type="textarea"
                rows="3"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="领料出库" v-if="title === '编辑'" name="2">
          <el-form
            ref="ruleFormOut"
            :model="ruleFormOut"
            :rules="rules"
            label-width="90px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="出库单号" prop="outNo">
                  <el-input
                    v-model="ruleFormOut.outNo"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出库日期" prop="outDate">
                  <el-date-picker
                    v-model="ruleFormOut.outDate"
                    type="date"
                    placeholder="选择日期时间"
                    style="width: 100%"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出库人" prop="userId">
                  <el-select
                    v-model="ruleFormOut.userId"
                    style="width: 100%"
                    filterable
                  >
                    <el-option
                      v-for="item in userAllList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="来料数量" prop="incomingNum">
                  <el-input v-model="ruleForm.incomingNum" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="缺料数量">
                  <el-input
                    :value="ruleForm.applyNum - ruleForm.incomingNum"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleFormOut.remark"
                type="textarea"
                rows="3"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-form>
          <el-table
            border
            class="tabOver"
            stripe
            height="220px"
            :data="materialList"
          >
            <el-table-column prop="materialId" label="物料" align="center">
              <template #default="{ row }"
                >{{ row.materialName }}
                {{
                  row.materialCode ? "【" + row.materialCode + "】" : ""
                }}</template
              >
            </el-table-column>
            <el-table-column
              prop="unit"
              label="单位"
              width="100px"
              align="center"
            />
            <el-table-column
              prop="num"
              label="数量"
              width="100px"
              align="center"
            />
            <el-table-column
              prop="batch"
              label="批号"
              width="150px"
              align="center"
            />
            <el-table-column
              prop="wmsName"
              label="仓库名称"
              width="150px"
              align="center"
            />
            <el-table-column prop="outNum" align="center" width="120px">
              <template slot="header">
                <span style="color: #f56c6c">*</span>出库数量
              </template>
              <template #default="{ row }">
                <el-input-number
                  v-model="row.outNum"
                  size="mini"
                  :controls="false"
                  :min="1"
                  :max="row.num"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
          </el-table>
          <p style="text-align: right">
            <el-button
              type="primary"
              icon="el-icon-check"
              v-if="materialList.length > 0"
              @click="submitFormOut('ruleFormOut')"
              >领料出库</el-button
            >
          </p>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <bottom-font
      v-if="title === '编辑'"
      ref="bottomFont"
      :obj-name="
        ruleForm.applyName
          ? ruleForm.applyName
          : this.$store.getters.compInfo.userName
      "
      :rew-name="ruleForm.reviewer ? ruleForm.reviewer : ''"
      :obj-date="ruleForm.createAt"
    />
  </el-dialog>
</template>
<script>
import TreeSelect from "@/components/TreeSelect";
import bottomFont from "@/components/BottomFont";
export default {
  components: { TreeSelect, bottomFont },
  props: {
    userAllList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    materialAll: {
      type: Array,
      default: () => {
        return [];
      },
    },
    factoryData: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    const checkPickNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/pro/pick/verifyNoUnique?no=${value}&id=${this.ruleForm.id || ""}`
      );
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback("领料单号重复！"));
      } else {
        return new Error(callback(res.data.msg));
      }
    };
    return {
      activeName: "1",
      title: "",
      ruleForm: {
        pickNo: "",
        applyId: "",
        materialId: "",
        applyNum: "",
        factoryId: "",
        remark: "",
      },
      rules: {
        materialId: [
          { required: true, message: "物料不能不能为空！", trigger: "change" },
        ],
        pickNo: [
          { required: true, message: "领料单号不能为空！", trigger: "blur" },
          { validator: checkPickNo, trigger: "blur" },
        ],
        applyId: [
          { required: true, message: "申请人不能为空！", trigger: "change" },
        ],
        applyNum: [
          { required: true, message: "申请数量不能为空！", trigger: "blur" },
        ],
        applyDate: [
          { required: true, message: "申请时间不能为空！", trigger: "blur" },
        ],
        factoryId: [
          { required: true, message: "作业车间不能为空！", trigger: "change" },
        ],
        userId: [
          { required: true, message: "出库人不能为空！", trigger: "change" },
        ],
        outNo: [
          { required: true, message: "出库单号不能为空！", trigger: "blur" },
        ],
        outDate: [
          { required: true, message: "出库日期不能为空！", trigger: "change" },
        ],
      },
      ruleFormOut: {
        outNo: "",
        outDate: "",
        userId: "",
        remark: "",
        materials: [],
      },
      dialogVisible: false,
      treeProps: {
        value: "id",
        label: "factoryName",
        children: "children",
      },
      materialList: [],
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      if (row && row.hasOwnProperty("id")) {
        this.title = "编辑";
        this.getDetail(row.materialId);
        this.ruleForm = { ...this.ruleForm, ...row };
      } else {
        this.title = "新增";
      }
      this.dialogVisible = true;
    },
    /* 编辑获取详情 */
    async getDetail(id) {
      const res = await this.$axios.get(`/pro/pick/searchMaterial?id=${id}`);
      if (res.data.code === 200) {
        this.materialList = res.data.data;
      }
    },
    /* 作业车间选择 */
    getValue(val) {
      this.ruleForm.factoryId = val.id;
    },
    /* 新增编辑表单提交 */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$axios.post("/pro/pick/save", this.ruleForm);
          if (res?.data.code === 200) {
            this.$notify.success("提交成功！");
            this.dialogVisible = false;
            this.$emit("getTableInfo");
          } else {
            this.$notify.error(res.data.msg);
          }
        }
      });
    },
    /* 领料表单提交 */
    submitFormOut(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.ruleFormOut.id = this.ruleForm.id;
          /* 判断库房出库数量必须有一条是填的 */
          let arr = [];
          this.materialList.forEach((item) => {
            if (item.outNum !== undefined) {
              arr.push(item);
            }
          });
          if (arr.length > 0) {
            const params = {
              ...this.ruleFormOut,
              materials: arr,
            };
            console.log(params);
            const res = await this.$axios.post("/pro/pick/outMaterial", params);
            if (res?.data.code === 200) {
              this.$notify.success("提交成功！");
              this.dialogVisible = false;
              this.$emit("getTableInfo");
            } else {
              this.$notify.error(res.data.msg);
            }
          } else {
            this.$alert(`请填写一条出库数量!`, "提示", {
              confirmButtonText: "确认",
              type: "warning",
            });
          }
        }
      });
    },
    /* 关闭窗口 */
    close() {
      this.resetForm("ruleForm");
      this.resetForm("ruleFormOut");
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = {
        pickNo: "",
        applyId: "",
        materialId: "",
        applyNum: "",
      };
      this.ruleFormOut = {
        outNo: "",
        outDate: "",
        userId: "",
        remark: "",
        materials: [],
      };
      this.activeName = "1";
    },
  },
};
</script>
<style lang="scss" scoped></style>
